package com.winkyle.woodenfish.util;

import android.content.Context;

import com.google.gson.GsonBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.winkyle.woodenfish.retrofit.Apis;

import java.util.concurrent.TimeUnit;

import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;

/**
 * @author winkyle
 * @date 2018/06/14
 * @description Retrofit初始化工具
 */

public class RetrofitUtil {
    private Context context;
    private OkHttpClient client;
    private Retrofit retrofit;
    private volatile static RetrofitUtil instance;

    /**
     * @description 单例模式，拒绝外部实例本类
     * @param context 上下文
     * @return
     */
    public static RetrofitUtil getInstance(Context context){
        if(instance == null){
            synchronized (RetrofitUtil.class){
                if(instance == null)
                    instance = new RetrofitUtil(context);
            }
        }
        return instance;
    }

    /**
     * @description 私有构造器
     * @param context 上下文
     * @return
     */
    private RetrofitUtil(Context context){
        this.context = context;
        initClient();
        initRetrofit();
    }

    /**
     * @description 创建OkHttpClient，设置最大连接时间，最大读取时间，增加Cookie拦截器
     * @return
     */
    private void initClient(){
        client = new OkHttpClient();
        client.setReadTimeout(7676, TimeUnit.MILLISECONDS);
        client.setConnectTimeout(7676,TimeUnit.MILLISECONDS);
        client.interceptors().add(new CookiesAddInterceptor(context));
        client.interceptors().add(new CookiesSavaInterceptor(context));
    }

    /**
     * @description 创建一个Retrofiti，并设置基地址，client,json解析器，异步解析器
     * @return
     */
    private void initRetrofit() {
        retrofit = new Retrofit.Builder()
                .baseUrl(Apis.Base)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }

    /**
     * @description 获取Retrofit
     * @return 一个 {@link Retrofit}类
     */
    public Retrofit getRetrofit() {
        return retrofit;
    }
}
